package cn.com.jrj.base.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;

import cn.com.jrj.base.exception.ApplicationException;


public class FileUtil {
	private static final FileUtil instance = new FileUtil();

	public static FileUtil getInstance() {
		return instance;
	}

	public boolean mkdir(String dir) {
		File file = new File(dir);
		if (file.exists() && file.isDirectory())
			return true;
		return file.mkdirs();
	}

	public boolean exists(String filePath) {
		File file = new File(filePath);
		return file.exists();
	}

	public void mv(String srcPath, String destPath) {
		File src = new File(srcPath);
		File dest = new File(destPath);
		if (!src.exists())
			return;

		src.renameTo(dest);
	}

	public File getFile(String path) {
		return new File(path);
	}

	public boolean delete(String filePath) {
		File file = new File(filePath);
		if (file.exists())
			return file.delete();
		else
			return true;
	}

	public Writer getFileWriter(String path) throws ApplicationException {
		File file = new File(path);
		if (!file.getParentFile().exists())
			return null;
		try {
			return new FileWriter(path);
		} catch (IOException e) {
			throw new ApplicationException(FileUtil.class + "#getFileWriter IOException", e);
		}
	}

	/**
	 * copy 文件基本操作
	 * 
	 * @param fins
	 * @param destine
	 */
	private boolean cp(InputStream fins, File destine) {
		try {
			if (fins == null)
				return false;
			destine.getParentFile().mkdirs();
			FileOutputStream fos = new FileOutputStream(destine);
			byte[] buf = new byte[1024];
			int readLen;
			while ((readLen = fins.read(buf, 0, buf.length)) > 0) {
				fos.write(buf, 0, readLen);
			}
			fos.flush();
			fos.close();
			fins.close();
		} catch (Exception ex) {
			return false;
		}
		return true;
	}

	/**
	 * copy 文件
	 * 
	 * @param src
	 * @param destine
	 */
	public boolean cp(File src, File destine) {
		try {
			if (!src.exists() || src.getCanonicalPath().equals(destine.getCanonicalPath()))
				return false;
			FileInputStream fins = new FileInputStream(src);
			cp(fins, destine);
			destine.setLastModified(src.lastModified());
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 将srcPath文件copy到desPath上
	 * 
	 * @param srcPath
	 * @param desPath
	 */
	public boolean cp(String srcPath, String desPath) {
		File src = new File(srcPath);
		File destine = new File(desPath);
		return cp(src, destine);
	}
	
	public boolean writeFile(String fileName,String Content)
	{
		try
		{
			FileWriter fw=new FileWriter(fileName);//true 追加
			fw.write(Content);
			fw.close();
			return true;
		}
		catch(Exception e)
		{
			return false;
		}
	}
}
